<template>
	<view class="">
		<view class="e-flex e-p-t-20 bg-white e-p-l-20">
			<view class="e-flex-1 c-333 e-font-24 fw-600">
				{{$t('classify.自提时间')}}
			</view>
			<view class="e-flex" @tap="show = true">
				<view class="e-m-r-20" :style="{color: AppSkin.primary}">
					{{time}}
				</view>
				<app-image src="arrow_right.png" :size="['36rpx']" />
			</view>
		</view>
		<view class="e-flex e-p-t-20 bg-white e-m-b-20 e-p-b-20 e-p-l-20" v-if="storeAddress">
			<view class="e-flex-1 c-333 e-font-28">
				{{$t('classify.自提门店')}}
			</view>
			<view class="e-flex" @tap="handleJumpSelfPoint({storeId:storeId,id:storeAddress.id})">
				<view class="e-m-r-20 e-font-24 c-secondary">
					{{$t('classify.更改自提点')}}
				</view>
				<app-image src="arrow_right.png" :size="['36rpx']" />
			</view>
		</view>
		<view class="self-point-box e-p-20">
			<view class="e-flex e-m-b-40" v-if="storeAddress"
				@tap="handleJumpSelfPoint({storeId:storeId,id:storeAddress.id})">
				<view class="" style="display: flex;width: 100%;">
					<view class="e-flex-1 e-m-r-30">
						<view class="e-font-28	c-333 fw-600 e-flex e-m-b-10	">
							<view class="e-flex-1 e-flex">
								<view v-if="storeAddress.labelName" class="label-box e-m-r-10"
									:style="{background:storeAddress.labelBackgroundColor,color:storeAddress.labelTextColor}">
									{{storeAddress.labelName}}
								</view>
								<text>{{storeAddress.name}}</text>
							</view>
						</view>
						<view class="e-font-24 c-secondary">
							{{storeAddress.detailedAddress}}
						</view>
					</view>
					<view class="">
						<view class="e-p-l-10 e-p-r-10 e-m-b-20" :style="[activitytitle]">
							{{$t('nearby.距您')}} {{storeAddress.distance | getDistance}}
						</view>
						<view class="e-rela e-flex e-p-r-50" style="justify-content: flex-end;">
							<text class="grey-posi" :style="{color:	AppSkin.primary}"></text>
							<image class="img-38-28" :src="$staticPath('grey_map.png')" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</view>
	
		<e-popup :show="show" round="20rpx" @close="close">
			<view class="nearby-store-address__popup">
				<view class="e-p-t-22 e-p-b-24 e-rela e-flex-xy-center">
					<text class="e-font-32 fw-500">{{ $t('nearby.选择预计到店时间') }}</text>
					<image src="/pages/systemPay/static/close.png" class="nearby-store-address__popup-icon img-28" @tap="close">
					</image>
				</view>
				<view class="nearby-store-address__popup-body e-flex e-flex-items-start">
					<view class="nearby-store-address__popup-day">
						<view class="e-flex-xy-center" :class="{ 'bg-white': dayType === 1 }" @tap="setDayType(1)"
							v-if="toTimeList.length">
							<text>{{ $t('nearby.今天') }}</text>
							<text>({{ $t('nearby.' + today) }})</text>
						</view>
						<view class="e-flex-xy-center" :class="{ 'bg-white': dayType === 2 }" @tap="setDayType(2)">
							<text>{{ $t('nearby.明日') }}</text>
							<text>({{ $t('nearby.' + tomorrow) }})</text>
						</view>
					</view>
					<view class="nearby-store-address__popup-time e-flex-1 bg-white">
						<scroll-view scroll-y="true">
							<view class="nearby-store-address__popup-time__item e-flex e-flex-between"
								v-for="(item, index) in timeArray" :key="index" @tap="timeIndex = index">
								<text :class="{ 'c-primary': timeIndex === index }">{{ item }}</text>
								<image src="/pages/systemPay/static/success.png" v-show="timeIndex === index"></image>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</e-popup>
	</view>
</template>
<script lang="ts">
	import {
		defineComponent
	} from 'vue'
	export default defineComponent({
		// #ifdef MP-WEIXIN
		// 将自定义节点设置成虚拟的，更加接近Vue组件的表现
		options: {
			virtualHost: true
		},
		// #endif
	})
</script>
<script setup lang="ts">
	import { ref, computed, watch } from 'vue'
	import type { DeliveryPlace } from '@/common/request/api'
	import { timeFormat, padZero } from '@/common/utils'
	import { useInit } from '@/common/stores'
	import { storeToRefs } from 'pinia'
	
	type ReceivingIds =  Array<{
			predictTime ?: string
			storeId : string
			storeAddress : DeliveryPlace
		}>
	const props = withDefaults(defineProps<{
		storeId : string
		receivingIds :ReceivingIds
	}>(), {})

	const emits = defineEmits(['setPredictTime','updateReceivingIds'])

	const { AppSkin } = storeToRefs(useInit())

	const time = ref('00:00')
	const show = ref(false)
	const today = ref('周一')
	const tomorrow = ref('周一')
	const toTimeList = ref<string[]>([])
	const timeList = ref<string[]>([])
	const timeIndex = ref(0)
	const dayType = ref(1)
	const storeAddress = ref<DeliveryPlace | null>(null)
	const activitytitle = computed(() => {
		return {
			background: AppSkin.value.primary.replace('1)', '0.1)'),
			color: AppSkin.value.primary
		}
	})

	const timeArray = computed(() => {
		return dayType.value === 1 ? toTimeList.value : timeList.value
	})

	const getDistance = (num : number) => {
		return num > 1000 ? `${(num / 1000).toFixed(1)}km` : `${num}m`
	}

	watch(time, () => {
		updatePredictTime()
	})
	watch(() => props.receivingIds, (val) => {

		if (val) {
			val.some(item => {
				if (item.storeId === props.storeId) {
					storeAddress.value = item.storeAddress
					getTimeList(storeAddress.value.businessHours)
					return true
				}
			})
		}
	}, {
		immediate: true,
		deep: true
	})


	const updatePredictTime = () => {
		const now = new Date()
		let _dd = now
		if (dayType.value == 2) {
			_dd = new Date(now.setDate(now.getDate() + 1))
		}
		const predictTime = `${timeFormat(_dd, 'yyyy-mm-dd')} ${time.value}`
		emits('setPredictTime', predictTime, props.storeId)
	}
	const close = () => {
		show.value = false
		time.value = timeArray.value[timeIndex.value]

	}
	const setDayType = (type : number) => {
		dayType.value = type
		timeIndex.value = 0
	}

	const getTimeList = (businessHours:string) => {
		
			toTimeList.value = []
			timeList.value = []
			const nowHours = new Date().getHours()
			const business_arr = businessHours.split('-')
			const business_arr1 = business_arr[0].split(':')
			const business_arr2 = business_arr[1].split(":")
			const startH = Number(business_arr1[0])
			const endH = Number(business_arr2[0])
			if (nowHours < startH) {
				for (let i = startH; i <= endH; i++) {
					toTimeList.value.push(`${padZero(i)}:00`)
				}
			} else if (nowHours > startH && nowHours < endH) {
				for (let i = nowHours+1; i <= endH; i++) {
					toTimeList.value.push(`${padZero(i)}:00`)
				}
			}
			for (let i = startH; i <= endH; i++) {
				timeList.value.push(`${padZero(i)}:00`)
			}
			
			const date = new Date()
			if (!toTimeList.value.length) {
				dayType.value = 2
			}
			today.value = `周${'日一二三四五六'.charAt(date.getDay())}`
			tomorrow.value = `周${'一二三四五六日'.charAt(date.getDay())}`
		
			close()
		
	}
	
	const updateSelfPickAddr = (data:DeliveryPlace) => {
		storeAddress.value = data
		getTimeList(data.businessHours)
		emits('updateReceivingIds',data)
		const receivingIds:ReceivingIds = uni.getStorageSync('receivingIds')
		if (receivingIds) {
			receivingIds.some((item,index) => {
				if (item.storeId === data.storeId) {
					receivingIds[index].storeAddress = data
				}
			})
			
			uni.setStorageSync('receivingIds', receivingIds)
		}
	}
	
	const handleJumpSelfPoint = (params:Record<string, any> ) => {
		ctx.$goTo('/pages/classify/self-point',params,{
			updateSelfPickAddr
		})
	}
	
</script>

<style lang="scss" scoped>
	.self-point-box {
		width: 100%;
		background: #F7F7F7;
		border-radius: 20rpx;
	}

	.nearby-store-address {
		padding: 32rpx 20rpx 22rpx 20rpx;

		&__icon {
			padding: 0 4rpx;
		}

		&__time {
			padding-right: 30rpx;
			position: relative;

			&::after {
				content: '';
				height: calc(100% - 20rpx);
				width: 2rpx;
				background-color: #e6e6e6;
				position: absolute;
				right: 0;
				top: 10rpx;
			}
		}

		&__add {
			overflow: hidden;
			padding-left: 28rpx;
		}

		&__popup {
			&-icon {
				position: absolute;
				right: 20rpx;
				top: 32rpx;
			}

			&-body {
				border-top: 2rpx solid #e2e2e2;
				background: #f7f7f7;
			}

			&-day {
				flex: 0 0 256rpx;

				>view {
					height: 94rpx;
				}
			}

			&-time {
				scroll-view {
					height: 468rpx;
				}

				&__item {
					padding: 0 20rpx 0 22rpx;
					height: 94rpx;

					image {
						width: 22rpx;
						height: 18rpx;
					}
				}
			}
		}
	}

	.customer-line {
		border-bottom: 2rpx solid #F2F2F2;
		margin-bottom: 20rpx;
	}

	.label-box {
		padding: 2rpx 6rpx;
		font-size: 20rpx;
		font-weight: 600;
		color: #FFFFFF;
		background: #03CBFD;
		border-radius: 4rpx;
	}

	.img-38-28 {
		width: 38rpx;
		height: 28rpx;
	}

	@font-face {
		font-family: "iconfont";
		/* Project id 3839120 */
		src: url('../../static/posiFont/iconfont.woff2?t=1680767609626') format('woff2'),
			url('../../static/posiFont/iconfont.woff?t=1680767609626') format('woff'),
			url('../../static/posiFont/iconfont.ttf?t=1680767609626') format('truetype');
	}

	.grey-posi {
		font-family: "iconfont" !important;
		font-size: 18rpx;
		font-style: normal;
		position: absolute;
		bottom:60%;
		left: 60%;
		z-index: 9;
		&:before {
			content: "\e62b";
		}
	}
</style>